<?php

namespace App\Console\Commands;

use Dcat\Admin\Console\GeneratorCommand;

class ControllerAdminCommand extends GeneratorCommand
{
    protected $signature = 'admin:controller {name}
        {--namespace=}
        {--model=}';

    protected $description = 'Create a new admin controller class';

    public function handle()
    {
        $this->askBaseDirectory();

        return parent::handle();
    }

    protected function getStub()
    {
        return base_path('stubs/controller.admin.stub');
    }

    protected function getDefaultNamespace($rootNamespace)
    {
        if ($namespace = $this->option('namespace')) {
            return $namespace;
        }

        return config('admin.route.namespace');
    }

    protected function getNameInput()
    {
        $name = trim($this->argument('name'));

        $this->type = $this->qualifyClass($name);

        return $name;
    }

    protected function buildClass($name)
    {
        $stub = $this->files->get($this->getStub());

        if ($model = $this->option('model')) {
            $model = 'App\\Models\\'.$model;
            $as = substr($model, strripos($model, '\\') + 1);

            $stub = str_replace(['DummyModel', '{{ model }}', '{{model}}'], $model, $stub);
            $stub = str_replace(['AsModel'], $as, $stub);
        }

        return $this->replaceNamespace($stub, $name)->replaceClass($stub, $name);
    }

}
